package com.czk.netty.nio.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * nio客户端
 *
 * @Author:ChenZhangKun
 * @Date: 2021/1/11 22:51
 */
public class NioClient {
    public static void main(String[] args) throws IOException {
        // 得到网络通道
        SocketChannel socketChannel = SocketChannel.open();
        // 设置非阻塞
        socketChannel.configureBlocking(false);
        // 连接服务器
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
        if (!socketChannel.connect(inetSocketAddress)) {
            while (!socketChannel.finishConnect()) {
                System.out.println("因为连需要时间，所以不必阻塞");

            }
        }
        // 连接成功
        String str = "czk你好";
        // 产生一个字节数组在buffer中
        ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
        // 将数据写入channel
        socketChannel.write(buffer);
        System.in.read();
    }
}
